package band.wukong.practice.webservice.kh.sample05.nongen;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.io.IOException;
import java.util.Set;

/**
 * @author wukong(wukonggg@139.com)
 */
public class JukeboxClientMessageHeaderHandler implements SOAPHandler<SOAPMessageContext> {

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        System.out.println("[Client][Handler] handleMessage");

        // 对于client，如果out是true，说明消息是要发送出去的，需要处理header；
        // 对于client，如果out是false，说明消息是接收进来的，不需要处理header。
        Boolean out = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (!out)   {
            return true;
        }

        SOAPMessage message = context.getMessage();
        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

            addHeader(envelope);// 在VIDEO21注释掉

            System.out.print("[Client][Handler] ");
            message.writeTo(System.out);
            System.out.println();

        } catch (SOAPException | IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    private void addHeader(SOAPEnvelope envelope) throws SOAPException {
        SOAPHeader header = envelope.getHeader();
        if (null == header) {
            header = envelope.addHeader();
        }

        QName qName = new QName(JukeboxConst.SERVICE_WSDL, "licenseInfo", "ns");
        header.addHeaderElement(qName).setValue("毛主席万岁");
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        System.out.println("[Client][Handler] handleFault");
        return false;
    }

    @Override
    public void close(MessageContext context) {
        System.out.println("[Client] [Handler] close");
    }
}
